package com.itheima.web.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Member;
import com.itheima.domain.store.OrderToTraveller;
import com.itheima.domain.store.Orders;
import com.itheima.domain.store.Traveller;
import com.itheima.service.store.MemberService;
import com.itheima.service.store.OrdersService;
import com.itheima.utils.BeanUtil;
import com.itheima.web.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/pages/orders")
public class OrdersServlet extends BaseServlet {
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int pageSize = 5;
        if(StringUtils.isNotBlank(request.getParameter("page"))){
            page = Integer.parseInt(request.getParameter("page"));
        }
        if(StringUtils.isNotBlank(request.getParameter("pageSize"))){
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        PageInfo all = ordersService.findAll(page, pageSize);
        //将数据保存到指定的位置
        request.setAttribute("ordersList",all);
        //跳转页面
        request.getRequestDispatcher("/pages/orders-list.jsp").forward(request,response);
    }

    public void delete(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //将数据获取到，封装成一个对象
        //Orders orders= BeanUtil.fillBean(request,Orders.class);
        //调用业务层接口save
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        ordersService.delete(id);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/pages/orders?operation=list");
    }

    public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询要修改的数据findById
        String id = request.getParameter("id");
        Orders orders = ordersService.findById(id);
        //将数据加载到指定区域，供页面获取
        request.setAttribute("orders",orders);

        String memberId = request.getParameter("memberId");

        Member member = memberService.findById(memberId);
        request.setAttribute("member",member);

        List<Traveller> list = orderToTravellerService.findById(id);
        request.setAttribute("orderToTraveller",list);

        //跳转页面
        request.getRequestDispatcher("/pages/orders-show.jsp").forward(request,response);
    }
}
